//
//  UIButton+XCCodeTimeButton.m
//  HMT-APP
//
//  Created by IOS技术专用 on 2017/9/8.
//  Copyright © 2017年 LXC. All rights reserved.
//

#import "UIButton+XCCodeTimeButton.h"

@implementation UIButton (XCCodeTimeButton)

- (void)buttonCode:(int)count andBlock:(void(^)(void))completeBlock
{
    @weakify(self)
    self.enabled = NO;
    [self setTitle:[NSString stringWithFormat:@"%02d秒",count] forState:UIControlStateNormal];
    
    __block dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0));
    dispatch_source_set_timer(timer, dispatch_walltime(NULL, 0), 1.0 * NSEC_PER_SEC, 0);
    
    NSDate *endTime = [NSDate dateWithTimeIntervalSinceNow:count];
    
    dispatch_source_set_event_handler(timer, ^{
        @strongify(self)
        int interval = [endTime timeIntervalSinceNow];
        if (interval > 0) {
            NSString *timeStr = [NSString stringWithFormat:@"%02d秒", interval];
            dispatch_async(dispatch_get_main_queue(), ^{
                @strongify(self);
                self.enabled = NO;
                [self setTitle:timeStr forState:UIControlStateNormal];
            });
        } else {
            dispatch_source_cancel(timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                @strongify(self);
                self.enabled = YES;
                [self setTitle:@"发送验证码" forState:UIControlStateNormal];
            });
        }
    });
    dispatch_resume(timer);
    
//    dispatch_time_t start = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC));
//    uint64_t interval = (uint64_t)(1.0 * NSEC_PER_SEC);
//    dispatch_source_set_timer(timer, start, interval, 0);
//    dispatch_source_set_event_handler(timer, ^{
//
//    });
//    dispatch_resume(timer);
}

@end
